<template>
  <div class="touchLogin-container">
    <el-form class="card-box login-form" autoComplete="on" :model="loginForm" :rules="loginRules" ref="loginForm" label-position="left">
      <h3 class="title">
        <span v-text="loginID"></span>
      </h3>
      <h3 class="orgTitle">
        <span v-text="orgName"></span>
      </h3>
      <el-form-item prop="username">
        <span class="svg-container svg-container_login">
          <icon-svg icon-class="yonghuming" />
        </span>
        <el-input name="username" type="text" v-model="loginForm.username" autoComplete="on" @focus="onFocuslogname" placeholder="请输入正确的用户名" />
      </el-form-item>
      <el-form-item prop="password">
        <span class="svg-container">
          <icon-svg icon-class="mima" />
        </span>
        <el-input name="password" :type="pwdType" @keyup.enter.native="handleLogin" v-model="loginForm.password" @focus="onFocuspassword" autoComplete="on" placeholder="请输入密码" />
        <span class='show-pwd' @click='showPwd'>
          <icon-svg icon-class="yanjing" />
        </span>
      </el-form-item>
      <el-button type="primary" :loading="$store.state.isloading" @click.native.prevent="handleLogin">登录</el-button>
      <el-button style="margin-top:20px; margin-left:-1px;" type="primary" :loading="$store.state.isloading" @click="openFinger">指纹登录</el-button>
    </el-form>
    <div class="div2">
      <div class="div3">
        <keyboard :option="option" @keyVal="getInputValue" @close="option.show = false"></keyboard>
      </div>
    </div>
    <sweet-modal ref="dialog" class="dialog">
      <h3>指纹登录</h3>
      <div style=" width:200px; margin:10px auto;">
      
        <img id="bmp" width="200" height="200" style=" border:solid gray 1px;" alt="指纹图像展示" />
      </div>
        <!-- <el-button type="primary"  @click="FPM_FeatureExtract_OnClick">指纹采集</el-button> -->
    </sweet-modal>
  </div>
</template>


<script>
// import { isvalidUsername } from '@/utils/validate'
import sweetModal from "@/components/sweetModal";
import { mapGetters } from "vuex";
import loginSafe from "@/assets/login/safe.jpeg";
import apiBase from "@/api/apiBase.js";
import encoding from "text-encoding";
import keyboard from "@/components/Keyboard/Keyboard";
const LOGNAME = "LOGNAME";
const PASSWORD = "PASSWORD";
//url参数 冷藏登记&寄存管理
const LCDJ = "lcdj";
const JCGL = "jcgl";
const WS_RET_ERR_OK = "0"; //操作成功
const WS_RET_ERR_PARAM = "-1"; //参数错误
const WS_RET_ERR_MEMORY = "-2"; //内存分配失败，没有分配到足够的内存
const WS_RET_ERR_FUN = "-3"; //功能未实现
const WS_RET_ERR_DEVICE = "-4"; //设备不存在
const WS_RET_ERR_INIT = "-5"; //设备未初始化
const WS_RET_ERR_UNKOWN = "-6"; //非法错误号
const WS_RET_ERR_TIEMOUT = "-7"; //超时
const WS_RET_ERR_ELSE = "-9"; //其它错误
const WS_FPM_Init = "FPM_Init";
const WS_FPM_Close = "FPM_Close";
const WS_FPM_GetDevVerison = "FPM_GetDevVerison";
const WS_FPM_GetSdkVerison = "FPM_GetSdkVerison";
const WS_FPM_FeatureExtract = "FPM_FeatureExtract";
const WS_FPM_GenFeature = "FPM_GenFeature";
const WS_FPM_FeatureMatch = "FPM_FeatureMatch";
global.fingerinfo = "";
export default {
  name: "login",
  data() {
    const validateUsername = (rule, value, callback) => {
      if (value == null) {
        callback(new Error("请输入正确的用户名"));
      } else {
        callback();
      }
    };
    const validatePassword = (rule, value, callback) => {
      if (value.length < 0) {
        callback(new Error("密码不能小于6位"));
      } else {
        callback();
      }
    };
    return {
      option: {
        show: false,
        sourceDom: ""
      },
      code: null,
      focusinput: null,
      loginForm: {
        username: "admin",
        password: ""
      },
      loginRules: {
        username: [
          {
            required: true,
            trigger: "blur",
            validator: validateUsername
          }
        ],
        password: [
          {
            required: true,
            trigger: "blur",
            validator: validatePassword
          }
        ]
      },
      pwdType: "password",
      loading: false,
      companys: [],
      pvdNo: null,
      timeout: null,
      loginID: null,
      codeErro: 0,
      codeValue: "",
      checkCode: "",
      codeTip: false,
      systemnameValue: false,
      orgName: null
    };
  },
  methods: {
    showPwd() {
      if (this.pwdType === "password") {
        this.pwdType = "";
      } else {
        this.pwdType = "password";
      }
    },
    getInputValue(val) {
      let intVal;
      if (!this.focusinput) return;
      if (this.focusinput === LOGNAME) intVal = this.loginForm.username;
      else if (this.focusinput === PASSWORD) intVal = this.loginForm.password;
      if (val === "delete") {
        intVal = intVal.slice(0, intVal.length - 1);
      } else {
        intVal += val;
      }
      if (this.focusinput === LOGNAME) this.loginForm.username = intVal;
      else if (this.focusinput === PASSWORD) this.loginForm.password = intVal;
    },
    onFocuslogname() {
      console.log(LOGNAME);
      this.focusinput = LOGNAME;
    },
    onFocuspassword() {
      this.focusinput = PASSWORD;
    },
    handleLogin(e) {
      //登录
      e.preventDefault();
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.$store.state.isloading = true;
          var data = {
            USRORGID: this.pvdNo,
            USRLOGINNAME: this.loginForm.username,
            USRPASSWD: this.loginForm.password
          };
          apiBase.DoService(
            data,
            apiBase.getApiAdress().Login.Login,
            res => {
              this.$store.state.sessionkey = res.data.content.SessionKey;
              this.$store.state.orginCode = res.data.content.OrganNumber;
              var sessionke = this.$store.state.sessionkey;
              this.$store.state.userAuthorization = localStorage.setItem(
                "Authorization",
                sessionke
              );
              var userName = localStorage.setItem(
                "name",
                this.loginForm.username
              );
              var orginCode = localStorage.setItem(
                "orginCode",
                res.data.content.OrganNumber
              );
              this.$store.state.loginPassword = this.loginForm.password;
              sessionStorage.setItem("loginForm", this.$route.fullPath);
              clearTimeout(this.timeout);
              this.timeout = setTimeout(() => {
                this.$store.state.isloading = false;
                if (this.$route.query.target === LCDJ) {
                  this.$router.push({
                    path: "/refrigerate"
                  });
                } else if (this.$route.query.target === JCGL) {
                  this.$router.push({
                    path: "/storage"
                  });
                } else {
                  this.$router.push({
                    path: "/touch"
                  });
                }
              }, 2000 * Math.random());
            },
            res => {
              this.$message.error("登录用户不存在或登录信息出错");
              this.$store.state.isloading = false;
              this.codeErro++;
              if (this.codeErro === 3) {
                this.codeErro = 0;
                this.loginForm.password = "";
              }
            }
          );
        }
      });
    },
    getCompany() {
      //获取所有机构
      this.orgName = null;
      var data = {};
      apiBase.DoService(data, apiBase.getApiAdress().Login.QueryOrgan, res => {
        this.companys = res.data.content;
        this.pvdNo = this.companys[0].ORGID;
        this.orgName = this.companys[0].ORGNAME;
        localStorage.setItem("orgname", this.orgName);
      });
    },
    getSystemname() {
      var data = {};
      this.loginID = "浙江省殡葬综合管理平台";
      document.title = this.loginID;
      localStorage.setItem("sysname", this.loginID);
      apiBase.DoService(
        data,
        apiBase.getApiAdress().Login.GetSystemname,
        res => {
          this.loginID = res.data.content.systemname;
          document.title = this.loginID;
          localStorage.setItem("sysname", this.loginID);
        }
      );
    },
    //指纹登录
    loginByFinger() {
      var data = {
        USKCONTEXT: global.fingerinfo
      };
      apiBase.DoService(
        data,
        apiBase.getApiAdress().Login.LoginByFingerPrint,
        res => {
          this.$store.state.sessionkey = res.data.content.SessionKey;
          this.$store.state.orginCode = res.data.content.OrganNumber;
          var sessionke = this.$store.state.sessionkey;
          this.$store.state.userAuthorization = localStorage.setItem(
            "Authorization",
            sessionke
          );
          var userName = localStorage.setItem("name", this.loginForm.username);
          var orginCode = localStorage.setItem(
            "orginCode",
            res.data.content.OrganNumber
          );
          this.$store.state.loginPassword = this.loginForm.password;
          sessionStorage.setItem("loginForm", this.$route.fullPath);
          clearTimeout(this.timeout);
          this.timeout = setTimeout(() => {
            this.$store.state.isloading = false;
            if (this.$route.query.target === LCDJ) {
              this.$router.push({
                path: "/refrigerate"
              });
            } else if (this.$route.query.target === JCGL) {
              this.$router.push({
                path: "/storage"
              });
            } else {
              this.$router.push({
                path: "/touch"
              });
            }
          }, 2000 * Math.random());
        },
        //指纹对比失败
         res => {
            this.$message.error(res.data.msg);
            document.querySelector('#bmp').src=null;
            this.FPM_FeatureExtract_OnClick();
         }
      );
    },
    //初始化设备
    FPM_Init() {
      var obj = {
        reqcode: "FPM_Init"
      };
      var str = JSON.stringify(obj);
      this.plguin_send(str);
      console.log("指纹设备已初始化");
    },
    //websocket连接设备，获取信息
    plguin_connect() {
      if (this.ws != null) {
        console.log("指纹设备现已连接");
        return;
      }
      let url = "ws://localhost:9032";
      if ("WebSocket" in window) {
        this.ws = null;
        this.ws = new WebSocket(url);
      } else if ("MozWebSocket" in window) {
        this.ws = new MozWebSocket(url);
      } else {
        console.log("unsupported WebSocket");
        return;
      }
      this.ws.onopen = function() {
        console.log("open");
        // setConnected("已连接");
        //设置发信息送类型为：ArrayBuffer
        this.binaryType = "arraybuffer";
      };
      this.ws.onmessage = this.websocketonmessage;


      this.ws.onclose = function(e) {
        this.ws = null;
        console.log("closed");
      };
      this.ws.onerror = function(e) {
        console.log("error");
        this.ws = null;
      };
    },
    //获取指纹信息
    websocketonmessage(e) {
     
        var s = e.data.toString();
        var obj = JSON.parse(s);
        if (obj.repcode == WS_FPM_FeatureExtract) {
          if (obj.result == WS_RET_ERR_OK) {
       
            document.querySelector("#bmp").src ="data:image/bmp;base64," + obj.image;
            global.fingerinfo = obj.feature;
            //指纹对比登录
            this.loginByFinger();
          }
        } else {
          console.log("Unkown");
        }
    },
    //断开连接
    plguin_close() {
      if (this.ws != null) {
        this.ws.close();
        this.ws = null;
        console.log("已断开");
      }
    },
    FPM_FeatureExtract_OnClick() {
      console.log("请按手指");
      var obj = {
        reqcode: "FPM_FeatureExtract",
        timeout: "10"
      };
      var str = JSON.stringify(obj);
      this.plguin_send(str);
    },
    FPM_Init_OnClick(){
        var obj = {"reqcode":"FPM_Init"};
        var str =JSON.stringify(obj);
        this.plguin_send(str);
    },
   
    FPM_GenFeature_OnClick() {
      var obt = {
        reqcode: "FPM_GenFeature",
        feature1: global.fingerinfo
      };
      var str = JSON.stringify(obt);

      this.plguin_send(str);
    },
    //websocket发送数据
    plguin_send(s) {
      if (this.ws != null) {
        this.ws.send(s);
      } else {
        console.log("[send]: ws null");
      }
    },
    //打开指纹登录页面
    openFinger() {
      document.querySelector('#bmp').src=null;
      this.FPM_Init_OnClick();
      this.FPM_FeatureExtract_OnClick();
      this.$refs.dialog.open();
    }
  },
  mounted() {
    this.FPM_Init();
    this.plguin_connect();
  },
  created() {
    this.getCompany();
    this.getSystemname();
    // window.location.reload()

    console.log("route", this.$route.fullPath);
  },
  computed: {
    ...mapGetters(["sessionkey"])
  },
  components: {
    keyboard,
    sweetModal
  }
};
</script>

<style rel="stylesheet/scss" lang="scss">
@import "src/styles/mixin.scss";
$bg: #2d3a4b;
$dark_gray: #889aa4;
$light_gray: #eee;
#code {
  font-family: Arial, 宋体;
  font-style: italic;
  color: green;
  border: 0;
  padding: 2px 3px;
  letter-spacing: 3px;
  font-weight: bolder;
  background: #e5e5e5;
  border-radius: 4px;
}
select::-ms-expand {
  //ie下啦箭头隐藏
  display: none;
}
.touchLogin-container .el-tabs__nav-scroll {
  .el-tabs__nav {
    width: 100%;
    .el-tabs__item {
      width: 51%;
    }
  }
}
.companyList {
  width: auto;
  display: inline-block;
  outline: medium none;
  border: none;
  -webkit-appearance: none;
  -moz-appearance: none;
  appearance: none;
  text-align: center;
  background-color: transparent;
  height: auto;
  padding: 6px 0px;
  font-size: 26px;
  line-height: normal;
  color: white;
  text-align-last: right;
}
.divLogin2 {
  width: 1200px;
  height: 500px;
  background-color: #fff;
  border-radius: 5px;
}
.div2 {
  position: absolute;
  width: 100%;
  bottom: 35px;
}
.div3 {
  margin: 0 auto;
  width: 1300px;
  height: 100px;
}
.touchLogin-container {
  box-sizing: border-box;
  @include relative;
  height: 100vh;
  background-color: $bg;
  background-image: url("touchloginBg.jpg");
  background-position: center;
  background-size: cover;
  input:-webkit-autofill {
    -webkit-box-shadow: 0 0 0px 1000px #293444 inset !important;
    -webkit-text-fill-color: #fff !important;
  }
  input {
    background: transparent;
    border: 0px;
    -webkit-appearance: none;
    border-radius: 0px;
    color: #fff;
    padding: 12px 5px 12px 15px; // color: $light_gray;
    height: 80px;
  }
  .el-button {
    width: 100%;
    height: 60px;
    font-size: 40px;
    letter-spacing: 10px;
    font-family: "Microsoft YaHei";
  }
  .el-form-item {
    margin-bottom: 40px;
  }
  .el-input {
    font-size: 30px;
    font-weight: bolder;
    display: inline-block;
    height: 80px;
    width: 85%;
  }
  .tips {
    font-size: 14px;
    color: #fff;
    margin-bottom: 10px;
  }
  .svg-container {
    padding: 15px 10px 10px 10px;
    color: $dark_gray;
    vertical-align: middle;
    width: 50px;
    vertical-align: top;
    display: inline-block;
    font-size: 50px;
  }
  .title {
    font-size: 45px;
    font-weight: 400;
    color: $light_gray;
    margin: 0px auto 20px auto;
    text-align: center;
    font-weight: bold;
  }
  .orgTitle {
    font-size: 30px;
    color: $light_gray;
    margin: 0px auto 20px auto;
    text-align: center;
    font-weight: bold;
  }
  .login-form {
    position: absolute;
    left: 0;
    right: 0;
    width: 1300px;
    padding: 35px 35px 15px 35px;
    margin: 20px auto;
  }
  .el-form-item {
    border: 1px solid rgba(255, 255, 255, 0.1);
    background: rgba(0, 0, 0, 0.1);
    border-radius: 5px;
    color: #454545;
  }
  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
  }
  .thirdparty-button {
    position: absolute;
    right: 35px;
    bottom: 28px;
  }
}
</style>
